<?php

namespace app\services;

use app\common\model\DateModel;
use app\common\model\StudentModel;
use PhpOffice\PhpSpreadsheet\IOFactory;
use think\Db;

class ExcelService
{
    /**
     * 读取excl数据
     */
    public static function import($filePath)
    {
        if (!realpath($filePath)) {
            return [];
        }
        //加载文件
        $spreadsheet = IOFactory::load($filePath);
        $sheetData = $spreadsheet->getActiveSheet()->toArray(true, true, true, true,true);

        $res = self::handleArrayData($sheetData);

        return $res;
    }
    /**
     * 处理数组数据
     */
    public static function handleArrayData($sheetData)
    {
//        dump($sheetData);die;
        //数组的长度
        $row_num = count($sheetData);
        $new_array = [];
        //遍历数组--去除不需要的数据
        for ($i=2; $i<=$row_num; $i++) {
            $new_array[$i]['name']   = $sheetData[$i]['B'];
            $new_array[$i]['type']   = $sheetData[$i]['C'];
            $new_array[$i]['time']   = $sheetData[$i]['E'];
//            $new_array[$i]['content']   = substr($sheetData[$i]['F'],50);
        }
        foreach ($new_array as $k => $v) {
            $new_array[$k]['date'] = self::changeTimeToDate($v['time']);
        }
        $model = new DateModel();
        $model->execute('truncate table date');
        $res = $model->saveAll($new_array);

        return $res;

    }

    /**
     *  将事件转化为具体某一天
     * @param $time
     * @return false|int|mixed|string
     */
    protected static function changeTimeToDate($time)
    {
        //替换年
        $time = str_replace('年','-',$time);
        //替换月
        $time = str_replace('月','-',$time);
        //替换日
        $time = str_replace('日','',$time);
        //分割日期和时间
        $arr = explode(' ',$time);
        $date = $arr[0];
        $time = $arr[1];
        //判断时间
        $arr = explode(':',$time);
        $hours = $arr[0];
        $minute = $arr[1];

        if ($hours < 8) {
            $date = date('Y-m-d',strtotime('-1 day',strtotime($date)));
        }
        if ($hours == 8 && $minute == 0) {
            $date = date('Y-m-d',strtotime('-1 day',strtotime($date)));
        }

        return $date;

    }
}